<template>
  <main-card-admin
    title="应用审核"
    class="applicationReview"
    :tabs="getTabs()"
    :loading="loading"
    :main-body-style-obj="{ paddingTop: '32px' }"
  >
    <template #screen-space>
      <a-row :align="'middle'" justify="space-between">
        <a-col>
          <condition-search
            :condition="[
              { name: '用户名称', key: 'username' },
              { name: '应用名称', key: 'name' }
            ]"
            @search="onSearch"
          />
        </a-col>
      </a-row>
    </template>
    <a-table
      :style="{ width: '100%' }"
      :columns="tableColumns"
      :data-source="logList"
      :pagination="false"
      :custom-row="(r:ListItem) => ({ onClick: () => previewClient(r) })"
      :row-key="(r:ListItem) => r.id"
      class="header-right-angle admin-table"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'tools'">
          <div class="button-group">
            <a-button @click.stop="openClient(record.id)">通过</a-button>
            <a-button @click.stop="openDisableModal(record as ListItem)">驳回</a-button>
          </div>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card-admin>
  <message-authorization
    v-model:show="showAuditModal"
    title="通过审核"
    msg="以下服务暂不支持授权，请确认应用是否通过审核"
    ok-text="确定"
    :data="authorizationPopData"
    @ok="confirmApproval"
  />
  <message-dialog
    v-model:show="showDisableModal"
    title="驳回审核"
    msg="此应用申请将被驳回，请确认操作！"
    label="请填写驳回原因"
    ok-text="确定"
    :del-task-loading="turnRequestLoading"
    @ok="disableClient"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { debounce } from 'g6-fn'
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'

  import ConditionSearch, { SearchFn } from '@/components/ConditionInput/index.vue'
  import MessageAuthorization from '@/components/MessageAuthorization/index.vue'
  import MessageDialog from '@/components/MessageDialog/index.vue'
  import useList from '@/hooks/use-list'
  import { applicationAuditApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import { ListItem, PageForm } from '../../types/index'
  import { getTabs } from '../../utils'

  const router = useRouter()

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '用户名称',
        dataIndex: 'username',
        width: 140
      },

      {
        title: '应用名称',
        dataIndex: 'name',
        width: 190
      },
      {
        title: '应用描述',
        dataIndex: 'content'
      },
      {
        title: '申请时间',
        dataIndex: 'createTime',
        width: 190,
        isSort: true
      },
      {
        title: '',
        dataIndex: 'tools',
        width: 168
      }
    ])
  )

  const {
    pageForm,
    loading,
    dataList: logList,
    getDataList
  } = useList<PageForm, ListItem>(applicationAuditApi.list, {
    username: '',
    name: '',
    customerId: '',
    columns: 'createTime',
    order: 'desc'
  })

  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1, order })
  }

  const onSearch: SearchFn = obj => {
    getDataList(obj)
  }

  const auditId = ref<string>('')
  const openClient = debounce(async (clientId: string) => {
    auditId.value = clientId
    loading.value = true
    try {
      const { data, code, message: resMessage } = await applicationAuditApi.approved({ id: clientId, flag: false }, { noJudgeCode: true })
      console.log(data, 'data')
      console.log(code, 'code')
      console.log(message, 'message')
      if (code === 'WAREHOUSE-100020' && data.length) {
        authorizationPopData.value = data
        showAuditModal.value = true
      } else if (code !== 'SYSTEM-100000') {
        message.error(resMessage)
        getDataList()
      } else {
        message.success('操作成功')
        getDataList()
      }
      loading.value = false
    } catch {
      loading.value = false
    }
  }, 500)

  const currentDisableItem = ref<ListItem>()
  const showDisableModal = ref(false)

  const authorizationPopData = ref<string[]>([])
  const showAuditModal = ref(false)
  const openDisableModal = async (item: ListItem) => {
    console.log(item, 'openDisableModal')

    currentDisableItem.value = item
    showDisableModal.value = true
  }

  // 驳回modal loading
  const turnRequestLoading = ref(false)
  const disableClient = debounce(async (text: string) => {
    turnRequestLoading.value = true
    try {
      await applicationAuditApi.reviewRejection({ id: currentDisableItem.value?.id, rejectReason: text })
      showDisableModal.value = false
      message.success('操作成功')

      getDataList()
      turnRequestLoading.value = false
    } catch {
      turnRequestLoading.value = false
    }
  }, 500)

  const confirmApproval = debounce(async () => {
    // console.log('confirmApproval')
    await applicationAuditApi.approved({ id: auditId.value, flag: true })
    showAuditModal.value = false
    message.success('操作成功')
    getDataList()
  }, 500)

  const previewClient = (item: ListItem) => {
    router.push({
      path: `/admin/app-check/check-list/detail/${item.id}`
    })
  }

  getDataList()
</script>

<style lang="less" scoped>
  .applicationReview {
    position: relative;

    .button-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
</style>
